
package com.pompom.matchcrawler;

import gummy.database.access.ConnectionSettingsPool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.LinkedList;

import nl.ansuz.android.steam.dota.request.economy.GetHeroes.Parameter;

import com.pompom.matchcrawler.types.TOWorker;
import com.pompom.workers.AbstractWorker;

public class JobManager {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		new JobManager();
	}
	
	private boolean stopWork=false;
	public JobManager()
	{
		
		
		SkillMapBuilder.build(new File("skillmap.map"));
//		long sb = SkillMapBuilder.getBuildFromArray(new int[]{
//				5028,5002,5028,5002,5028,5030,5028,5029,5027,5027,5030,5027,5027,5029,5029,5030 
//		},8);
//		System.out.println(sb);
//		SkillMapBuilder.testMap(sb);
		WorkerInitializer wa = new WorkerInitializer();

		LinkedList<AbstractWorker> allWorkers = new LinkedList<AbstractWorker>();
		try {
			FileInputStream fis = new FileInputStream(new File("jobs.xml"));

	//	wa.loadJobs(WorkerInitializer.class.getResourceAsStream("/jobs.xml"));
			wa.loadJobs(fis);
		} catch (FileNotFoundException e1) { 
			e1.printStackTrace();
		}

		ConnectionSettingsPool.getInstance().loadConnections(MatchPersistor.class.getResourceAsStream("/database.xml"));

		ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();

		for (int i=0;i<wa.getWorkers().length;i++)
		{
			TOWorker worker = wa.getWorkers()[i];

			for (int k=0;k<worker.instances;k++)
			{
				Class workerClass = null;
				try {
					workerClass = myClassLoader.loadClass(worker.workerClass);


					AbstractWorker instance =(AbstractWorker) workerClass.newInstance();
					//instance.lastExecution=System.currentTimeMillis();
					instance.sleepTimeSec = worker.sleepTimeSec;
					instance.sleepTimeMinutes = worker.sleepTimeMinutes;
					instance.jobClass = worker.workerClass;
					instance.setJobManager(this);
					MultiInstanceManager.registerMe(instance);
					if (worker.parameters!=null)
					{
						for (int j=0;j<worker.parameters.length;j++)
						{
							instance.putParameter(worker.parameters[j].name, worker.parameters[j].value);
						}

					}
					instance.setParameters();

					if (!worker.skipJob)
						allWorkers.add(instance);

				} 
				catch (Exception e) { 
					e.printStackTrace();
				}
			}



		}


		try{
			PrintWriter writer = new PrintWriter("jobman.ctl", "UTF-8");
			writer.println("gluglu"); 
			writer.close();

			System.out.println("Created control file");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Control file cannot be created ! Aborting");
			return;
		}






		for (int i=0;i<allWorkers.size();i++)
		{
			AbstractWorker job = allWorkers.get(i);
			Thread t = new Thread(job);
			t.start();

		}


		while(true)
		{


			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


			String fileName = "jobman.ctl";
			File f = new File(fileName);


			if (!f.exists())
			{
				System.out.println("Control file deleted ! quitting ...");
				break;
			}
		}
		this.setStopWork(true);

		for (int i=0;i<allWorkers.size();i++)
		{
			AbstractWorker job = allWorkers.get(i);
			job.setStopWork(true);

		}




		String fileName = "jobman.ctl";
		File f = new File(fileName);
		if (f.exists())
		{
			System.out.println("Weird... file exists but left loop.");
			System.out.println(" res: "+f.delete());
		}

		System.out.println("Terminating crawler.");


	}
	
	public void addWorker(AbstractWorker a)
	{
		
		Thread t = new Thread(a);
		t.start();
	}

	public boolean isStopWork() {
		return stopWork;
	}

	public void setStopWork(boolean stopWork) {
		this.stopWork = stopWork;
	}

}
